package cn.com.taiji.oospub.wechat.common.authdeny;

import cn.com.taiji.oospub.wechat.common.MyX509TrustManager;
import net.sf.json.JSONObject;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

public class NetTools {
	/**
     * 发送https请求
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("连接异常，超时；"+ce.getMessage());
        } catch (Exception e) {
        	System.out.println("https请求异常："+e.getMessage());
        }
        return jsonObject;
    }
    
    /** 
     * 向指定URL发送GET方法的请求 
     *  
     * @param url 
     *            发送请求的URL 
     * @param params 
     *            请求参数，请求参数应该是name=value&name=value的形式。 
     * @return URL所代表远程资源的响应 
     * 
     */ 
    public  String sendGet(String url, String params){  
        String result = "";  
        BufferedReader in = null;  
        try  
        {  
            String urlName = url + "?" + params; 
            URL realUrl = new URL(urlName);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent",  
                    "Mozilla/. (compatible; MSIE .; Windows NT .; SV)");  
            // 建立实际的连接  
            conn.connect();  
            // 获取所有响应头字段  
            Map<String, List<String>> map = conn.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : map.keySet())  
            {  
                System.out.println(key + "--->" + map.get(key));  
            }  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null)  
            {  
                result += "\n" + line;  
            }  
        } catch (Exception e)  {  
            System.out.println("发送GET请求出现异常！" + e);  
            e.printStackTrace();  
        }  finally  {  
            try  {  
                if (in != null){  
                    in.close();  
                	}  
            	}  
	        catch (IOException ex)  
	        {  
	            ex.printStackTrace();  
	        }  
        }  
        return result;  
    }
    /**  
     * 向指定URL发送POST方法的请求  
     *   
     * @param url  
     *            发送请求的URL  
     * @param params  
     *            请求参数，请求参数应该是name=value&name=value的形式。  
     * @return URL所代表远程资源的响应  
     */  
    public static String sendPost(String url, String params)  
    {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try  
        {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent",  
                    "Mozilla/. (compatible; MSIE .; Windows NT .; SV)");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());  
            // 发送请求参数  
            out.print(params);  
            // flush输出流的缓冲  
            out.flush();  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null)  
            {  
                result += "\n" + line;  
            }  
        }  
        catch (Exception e)  
        {  
            System.out.println("发送POST请求出现异常！" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输出流、输入流  
        finally  
        {  
            try  
            {  
                if (out != null)  
                {  
                    out.close();  
                }  
                if (in != null)  
                {  
                    in.close();  
                }  
            }  
            catch (IOException ex)  
            {  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }  
    
    
    //--------孤傲苍蓝------
    /**
          * 发起Https请求
          * @param reqUrl 请求的URL地址
          * @param requestMethod
          * @return 响应后的字符串
          */
   public  String getHttpsResponse(String reqUrl, String requestMethod) {
             URL url;
             InputStream is;
             String resultData = "";
             try {
                 url = new URL(reqUrl);
                 HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
                 TrustManager[] tm = {xtm};
     
                 SSLContext ctx = SSLContext.getInstance("TLS");
                 ctx.init(null, tm, null);
     
                 con.setSSLSocketFactory(ctx.getSocketFactory());
                 con.setHostnameVerifier(new HostnameVerifier() {
                     @Override
                     public boolean verify(String arg0, SSLSession arg1) {
                         return true;
                     }
                 });
     
     
                 con.setDoInput(true); //允许输入流，即允许下载
     
                 //在android中必须将此项设置为false
                 con.setDoOutput(false); //允许输出流，即允许上传
                 con.setUseCaches(false); //不使用缓冲
                 if (null != requestMethod && !"".equals(requestMethod)) {
                     con.setRequestMethod(requestMethod); //使用指定的方式
                 } else {
                     con.setRequestMethod("GET"); //使用get请求
                 }
                 is = con.getInputStream();   //获取输入流，此时才真正建立链接
                 InputStreamReader isr = new InputStreamReader(is);
                 BufferedReader bufferReader = new BufferedReader(isr);
                 String inputLine;
                 while ((inputLine = bufferReader.readLine()) != null) {
                     resultData += inputLine + "\n";
                 }
                 System.out.println(resultData);
     
             } catch (Exception e) {
                 e.printStackTrace();
             }
             return resultData;
         }
     
         X509TrustManager xtm = new X509TrustManager() {
             @Override
             public X509Certificate[] getAcceptedIssuers() {
                 return null;
             }
     
             @Override
             public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                     throws CertificateException {
     
             }
     
             @Override
             public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                     throws CertificateException {
     
             }
         };
    
 
  
  
}
